---
import BaseLayout from "@layouts/BaseLayout.astro";
import HorizontalCard from "@components/HorizontalCard.astro";
import { getCollection } from "astro:content";

export async function getStaticPaths({ paginate }) {
  const all_posts = await getCollection("blog");
  const all_tags = all_posts.flatMap((post) => {
    return post.data.tags || [];
  });

  return all_tags.flatMap((tag) => {
    const filtred_posts = all_posts.filter((post) => {
      return post.data.tags?.includes(tag);
    });
    return paginate(filtred_posts, {
      params: { tag },
      pageSize: 10,
    });
  });
}

const { page } = Astro.props;
const params = Astro.params;
---

<BaseLayout title={"Blog - " + params.tag} sideBarActiveItemID="blog">
  <div class="mb-5">
    <div class="text-3xl w-full font-bold">Blog - {params.tag}</div>
  </div>
  {
    page.data.length === 0 ? (
      <div class="bg-base-200 border-l-4 border-secondary w-full p-4 min-w-full">
        <p class="font-bold">Sorry!</p>
        <p>There are no blog posts to show at the moment. Check back later!</p>
      </div>
    ) : (
      <ul>
        {page.data.map((post) => (
          <>
            <HorizontalCard
              title={post.data.title}
              img={post.data.heroImage}
              desc={post.data.description}
              url={"/blog/" + post.slug}
              target="_self"
              badge={post.data.badge}
              tags={post.data.tags}
            />
            <div class="divider my-0" />
          </>
        ))}
      </ul>
    )
  }

  <div class="flex justify-between">
    {
      page.url.prev ? (
        <a href={page.url.prev} class="btn btn-ghost my-10 mx-5">
          {" "}
          <svg
            class="h-6 w-6 fill-current md:h-8 md:w-8"
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
          >
            <path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" />
          </svg>{" "}
          Recent posts
        </a>
      ) : (
        <div />
      )
    }
    {
      page.url.next ? (
        <a href={page.url.next} class="btn btn-ghost my-10 mx-5">
          Older Posts{" "}
          <svg
            class="h-6 w-6 fill-current md:h-8 md:w-8"
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
          >
            {" "}
            <path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
          </svg>
        </a>
      ) : (
        <div />
      )
    }
  </div>
</BaseLayout>
